package com.sunday.aomicaichang.ui.order;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.aomicaichang.R;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.OrderProduct;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderDetailActivity extends BaseActivity {

    @Bind(R.id.order_status)
    TextView orderStatus;
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_addr)
    TextView userAddr;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.total_money)
    TextView totalMoney;
    @Bind(R.id.order_num)
    TextView orderNum;
    @Bind(R.id.order_no)
    TextView orderNo;
    @Bind(R.id.order_time)
    TextView orderTime;
    @Bind(R.id.ly_msg)
    RelativeLayout lyMsg;
    @Bind(R.id.send_money)
    TextView sendMoney;
    @Bind(R.id.msg)
    TextView msg;
    @Bind(R.id.btn_confirm)
    TextView btnConfirm;
    @Bind(R.id.reduce)
    TextView reduce;
    @Bind(R.id.call)
    LinearLayout call;
    @Bind(R.id.message)
    TextView message;
    @Bind(R.id.send_massage)
    TextView sendMassage;
    private long orderId;
    private OrderItem orderItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        orderId = getIntent().getLongExtra("orderId", 0);
        getData();
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmRecieveOrder(orderId);
            }
        });
        call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("提示");
                builder.setMessage("是否拨打客服电话 010-56057691" + " ?" + "\n" + "\n" + "Tip:如果不能正常跳转，请到安全中心检查是否禁用此app拨号权限");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        String tel = "010-56057691";
                        Uri data = Uri.parse("tel:" + tel);
                        intent.setData(data);
                        startActivity(intent);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });
    }

    private void confirmRecieveOrder(Long orderId) {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"orderId", "nonce"};
        String[] str2 = new String[]{String.valueOf(orderId), nonce};
        Call<ResultDO> call = MemberClient.getApiAdapter().confirmReceive(orderItem.getId(), nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    getData();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage() + "");
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"orderId", "nonce"};
        String[] str2 = new String[]{String.valueOf(orderId), nonce};
        showLoadingDialog(0);
        Call<ResultDO<OrderItem>> call = MemberClient.getApiAdapter().getOrderDetail(orderId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<OrderItem>>() {
            @Override
            public void onResponse(Call<ResultDO<OrderItem>> call, Response<ResultDO<OrderItem>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    orderItem = response.body().getResult();
                    updateView();

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<OrderItem>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void updateView() {
        if (orderItem == null) {
            return;
        }
        if (orderItem.getShopName() != null)
            tv.setText(orderItem.getShopName());
        if (orderItem.getOrderStatus() == ConstValue.STA_THREE) {
            btnConfirm.setVisibility(View.VISIBLE);
        } else {
            btnConfirm.setVisibility(View.GONE);
        }
        if(orderItem.getRemark()!=null)
        message.setText("买家留言： "+orderItem.getRemark());
        else
            message.setText("买家留言：  暂无");
        if(orderItem.getDriverName()!=null||orderItem.getDriverMobile()!=null)
            sendMassage.setText("配送信息： "+orderItem.getDriverName()+"  "+orderItem.getDriverMobile());
        else
            sendMassage.setText("配送信息：  暂无");
        if(orderItem.getOrderStatusStr()!=null)
        orderStatus.setText(orderItem.getOrderStatusStr());
        if(orderItem.getReceiveName()!=null||orderItem.getReceiveMobile()!=null)
        userName.setText(String.format("%1$s  %2$s", orderItem.getReceiveName(), orderItem.getReceiveMobile()));
        if(orderItem.getReceiveAddress()!=null)
        userAddr.setText(orderItem.getReceiveAddress());
        if (orderItem.getOrderNo() != null)
            orderNo.setText(orderItem.getOrderNo());
        if (orderItem.getCreateTime() != null)
            orderTime.setText(orderItem.getCreateTime());
        if (orderItem.getPromotionMsg() != null) {
            lyMsg.setVisibility(View.VISIBLE);
            msg.setText(orderItem.getPromotionMsg() + "");
        } else {
            lyMsg.setVisibility(View.GONE);
        }
        if (orderItem.getSendAmount() != null) {
            sendMoney.setText(orderItem.getSendAmount() + "元");
        } else {
            sendMoney.setText("0元");
        }
        listView.setAdapter(new CommenAdapter<OrderProduct>(mContext, orderItem.getProducts(), R.layout.list_order_confirm_product) {
            @Override
            public void convert(ViewHolder helper, OrderProduct item, int position) {
                bind(helper, item);
            }
        });
        int num = 0;
        if (orderItem.getProducts() != null && orderItem.getProducts().size() > 0) {
            for (OrderProduct product : orderItem.getProducts()) {
                num += product.getNum();
            }
        }
        if (orderItem.getPayAmount().compareTo(new BigDecimal("0.00")) == 0) {
            totalMoney.setText("");
            totalMoney.append(SpannalbeStringUtils.setTextColor(String.format("￥%s", orderItem.getTotalAmount().setScale(2, RoundingMode.HALF_UP)), mContext.getResources().getColor(R.color.price_yellow)));

        } else {
            totalMoney.setText("");
            totalMoney.append(SpannalbeStringUtils.setTextColor(String.format("￥%s", orderItem.getPayAmount().setScale(2, RoundingMode.HALF_UP)), mContext.getResources().getColor(R.color.price_yellow)));
        }
    }

    private void bind(ViewHolder helper, OrderProduct item) {
        ImageView imageView = helper.getView(R.id.product_img);
        if (!TextUtils.isEmpty(item.getImage())) {
            Picasso.with(mContext)
                    .load(item.getImage())
                    .error(R.mipmap.ic_product)
                    .resize(150, 150)
                    .into(imageView);
        }
        ((TextView) helper.getView(R.id.product_title)).setText(item.getName());
        ((TextView) helper.getView(R.id.product_price)).setText(String.format("￥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) helper.getView(R.id.product_num)).setText(String.format("X%d", item.getNum()));
        ((TextView) helper.getView(R.id.product_spec)).setText(item.getStandard());
    }

}
